package com.homevip.web.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.homevip.core.controller.BaseController;
import com.homevip.util.UploadFile;
import com.homevip.util.UserSessionUtil;
import com.homevip.util.gson.JsonUtil;
import com.homevip.util.system.Const;
import com.homevip.web.vo.UploadResultVo;

/**
 * 上传
 * 考虑旧文件删除和多余上传的无用文件
 */
@Controller
public class UploadController extends BaseController {

	/**
	 * @throws Exception 
	 * @throws IOException
	 * 
	 *             方法名: upload <br />
	 *             描述: 上传文件<br />
	 *             参数：<br />
	 * @param request
	 * @param response
	 * <br />
	 * @return void <br />
	 * @throws
	 */
	@RequestMapping(value = "/uploadfile")
	public void uploadfile(HttpServletRequest request, HttpServletResponse response) throws Exception {
		if(null == UserSessionUtil.getUser(request)){
			writeJson(response, JsonUtil.toJson(new UploadResultVo(false, "无效参数", "", "")));
			return;
		}
		final String uploadPath = Const.UPLOAD_FLODER_ROOT;
		final String uploadUrl = Const.UPLOAD_URL_ROOT;
		
		try{
			String from = getString("from", request), dir = getString("dir", request), filetype = getString("filetype", request);
			
			if(!"".equals(dir)){
				dir = "/" + dir;
			}
			String fullUploadPath = uploadPath + dir + "/"; 
			String fullUploadUrl = uploadUrl + dir + "/";
			UploadFile up = new UploadFile(request, fullUploadPath);
			if (from.equals("kindeditor")) {// 编辑器返回参数不一样
				Map<String, Object> map = new HashMap<String, Object>();
				try {
					up.saveEditorFile(filetype);
					if (null!=up.saveFile && up.saveFile.exists()) {
						map.put("error", 0);
						map.put("url", fullUploadUrl + up.fileName);
					} else {
						map.put("error", 1);
						map.put("message", "上传失败！");
					}
				} catch (Exception e) {
					map.put("error", 1);
					map.put("message", e.getMessage());
				}
				writeHtml(response, JsonUtil.toJson(map));
			} else {
				UploadResultVo vo;
				up.saveFile();
				if (null!=up.saveFile && up.saveFile.exists()) {
					vo = new UploadResultVo(up.fileName, fullUploadUrl + up.fileName, up.oriName);
				} else {
					vo = new UploadResultVo(false, "上传失败", "", "");
				}
				writeJson(response, JsonUtil.toJson(vo));
			}
		}catch(Exception exp){
			writeJson(response, JsonUtil.toJson(new UploadResultVo(false, "无效参数", "", "")));
		}
	}
}
